<template>
  <a-modal
      :title="title"
      :width="1400"
      :visible="visible"
      :confirmLoading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
      cancelText="关闭">

    <a-spin :spinning="confirmLoading">
      <!--计费规则配置-->
      <a-row v-show="!EditForm">
        <!--计费规则表格-->
        <a-col :span="15">
          <a-table
              ref="table"
              size="middle"
              bordered
              rowKey="id"
              :columns="chargeRulesColumns"
              :dataSource="chargeRules"
              :pagination="ipagination"
              :loading="confirmLoading"
              @change="handleTableChange">
            <span slot="carTypeId" slot-scope="text,record">
              {{ carTypeIdTrans(text) }}
            </span>
            <span slot="action" slot-scope="text,record">
              <a @click="chargeRulesEdit(record)">配置详细计费信息</a>
              <a-divider type="vertical"></a-divider>
              <a @click="chargeRuleEdit(record)">编辑</a>
              <a-divider type="vertical"/>
              <a @click="chargeRuleDelete(record)">删除</a>
            </span>
          </a-table>

          <a-col :gutter="18">
            <a-col :gutter="18">
              <a-col>
                测试计费金额
              </a-col>
            </a-col>
            <a-col :md="6" :sm="6">
              <a-form-item>
                <a-date-picker
                    :showTime="true"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-dd HH:mm:ss"
                    placeholder="开始日期"
                    @change="onChangeStartTime"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="6">
              <a-form-item>
                <a-date-picker
                    :showTime="true"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-dd HH:mm:ss"
                    placeholder="结束日期"
                    @change="onChangeEndTime"
                    @ok="queryChargeFee"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="6">
              <a-form-item :labelCol="labelCol" label="计费结果">
                <a-input v-model="totalFee" style="width: 100px" :value="0">
                </a-input>
              </a-form-item>
            </a-col>
          </a-col>
        </a-col>
        <!--计费规则编辑区-->
        <a-col :offset="1" :span="8" >
          <a-row>
            <a-form :form="chargeRulesForm">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="选择车辆类型">
                <a-select style="width: 100px" :options="CarTypeSelectOption"
                          v-decorator="['carTypeId',{ rules: [{ required: true, message: '请选择车辆类型' }] }]"
                          @change="getChargeRule">
                </a-select>
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="每日最高限额">
                <a-input-number :min="0" :max="10000" v-decorator="['dayLimit',{initialValue:0}]">
                </a-input-number>
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="每日最高限额启用">
                <a-input v-show="false" v-decorator="['dayLimitEnable',{initialValue:1}]"></a-input>
                <a-checkbox :checked="dayLimitEnable===1" @change="dayLimitEnableChange"></a-checkbox>
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="免费时间">
                <a-input-number :min="0" :max="1440" v-decorator="['freeTime',{initialValue:0}]">
                </a-input-number>
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="免费时间启用">
                <a-input v-show="false" v-decorator="['freeTimeEnable',{initialValue:1}]"></a-input>
                <a-checkbox :checked="freeTimeEnable===1" @change="freeTimeEnableChange"></a-checkbox>
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="过夜类型">
                <a-select v-decorator="['twentyfourHourEnable',{initialValue:1}]" :options="divideType">

                </a-select>

              </a-form-item>
            </a-form>
          </a-row>

          <a-row>
            <a-col :span="24">
              <a-button style="width: 100%;" type="primary" @click="saveChargeRule">保存</a-button>
            </a-col>
          </a-row>
        </a-col>
      </a-row>
      <!--计费规则模块配置-->
      <a-row v-show="EditForm">
        <charge-rules-module-modal ref="chargeRulesModuleModal" @returnBack="editOk" ></charge-rules-module-modal>
      </a-row>
    </a-spin>
  </a-modal>
</template>

<script>
import {deleteAction, getAction, httpAction, postAction} from '@api/manage'
import ChargeRulesModuleModal from "@views/area/chargeRulesModule/modules/ChargeRulesModuleModal";
import pick from 'lodash.pick'

export default {
  name: "ChargeRulesModal",
  components:{
    ChargeRulesModuleModal
  },
  data() {
    return {
      title: "操作",
      visible: false,
      area: {},
      confirmLoading: false,
      chargeRulesForm: this.$form.createForm(this),
      labelCol: {
        xs: {span: 24},
        sm: {span: 8},
        style: 'textAlign:left'
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16},
      },
      moduleLabelCol: {
        xs: {span: 20},
        sm: {span: 12},
        style: 'textAlign:left'
      },
      moduleWrapperCol: {
        xs: {span: 28},
        sm: {span: 12},
        style: 'textAlign:right'
      },
      url: {
        addChargeRule: "/parking/chargeRules/add",
        editChargeRule: "/parking/chargeRules/edit",
        carTypeList: "/ConfigCarType/configCarType/getTemporaryCarList",
        getChargeRules: '/parking/chargeRules/list',
        getChargeRule: '/parking/chargeRules/getChargeRule',
        chargeRuleDelete: '/parking/chargeRules/delete',

        testCharge:'/parking/chargeRules/testCharge',
      },

      chargeRulesColumns: [
        {
          title: '车辆类型',
          align: "center",
          dataIndex: 'carTypeId',
          scopedSlots: {customRender: 'carTypeId'}
        },
        {
          title: '每天最高限额',
          align: "center",
          width: 110,
          dataIndex: 'dayLimit',
          customRender: function (t, r, index) {
            return parseInt(t / 100) + '元';
          }
        },
        {
          title: '每天最高限额状态',
          align: "center",
          width: 130,
          dataIndex: 'dayLimitEnable',
          customRender: function (t, r, index) {
            return t === 1 ? '启用' : '未启用';
          }
        },
        {
          title: '免费时间',
          align: "center",
          dataIndex: 'freeTime',
          customRender: function (t, r, index) {
            return t + '分钟';
          }
        },
        {
          title: '免费时间状态',
          align: "center",
          dataIndex: 'freeTimeEnable',
          customRender: function (t, r, index) {
            return t === 1 ? '启用' : '未启用';
          }
        },
        {
          title: '过夜类型',
          align: "center",
          dataIndex: 'twentyfourHourEnable',
          customRender: function (t, r, index) {
            if(t===1)
            {
              return '24小时后过夜'
            }
            if(t===2)
            {
              return "每日0点过夜"
            }
            if(t===3)
            {
              return "不跨夜"
            }
          }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: "center",
          scopedSlots: {customRender: 'action'},
        }
      ],
      chargeRules: [],
      chargeRule: {},
      ipagination: {
        current: 1,
        pageSize: 6,
        pageSizeOptions: ['6'],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条"
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      CarTypeSelectOption: [],
      areaId: '',
      parkCode: '',
      chargeType: 1,
      dayLimitEnable: 1,
      freeTimeEnable: 1,
      EditForm: false,
      carEnterTime:'',
      carOutTime:'',
      totalFee:0,
      divideType:[{value:1,label:"停车时间每超过24小时过夜"},{value:2,label:"当日24点过夜"},{value:3,label:"不跨夜"}]
    }
  },
  created() {
  },
  methods: {
    onChangeStartTime(value,dateString){ //
      this.carEnterTime = dateString
    },
    onChangeEndTime(value,dateString){
      this.carOutTime = dateString
    },
    queryChargeFee(){
      let params = {}
      params.areaId = this.chargeRule.areaId
      params.carTypeId = this.chargeRule.carTypeId
      params.carEnterTime = this.carEnterTime
      params.carOutTime = this.carOutTime
      getAction('/parking/chargeRules/testCharge', params).then((res) => {
        if(res.success)
        {
          this.totalFee = res.result/100
        }else {
          this.$message.error("获取测试金额失败")
        }
      })
    },
    add() {
      this.edit({});
    },
    async edit(record) {
      this.chargeRulesForm.resetFields();
      this.area = Object.assign({}, record);
      this.visible = true;
      this.areaId = record.id
      this.parkCode = record.parkCode
      this.reset()
      await this.getCarType(record)
      await this.getChargeRules(record)
    },
    reset() {
      this.chargeType = 1
      this.dayLimitEnable = 1
      this.freeTimeEnable = 1
      this.chargeRule = {}
      this.chargeRuleModule = {}
      this.chargeRulesForm.resetFields(['dayLimit', 'dayLimitEnable', 'twentyfourHourEnable', 'freeTime', 'freeTimeEnable'])
      this.EditForm = false
    },
    handleOk() {
      const that = this;
      // 触发表单验证
      this.chargeRulesForm.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true;
          let httpurl = '';
          let method = '';
          if (!this.area.id) {
            httpurl += this.url.addChargeRule;
            method = 'post';
          } else {
            httpurl += this.url.editChargeRule;
            method = 'put';
          }
          let formData = Object.assign(this.chargeRule, values);
          //时间格式化
          formData.updateTime = formData.updateTime ? formData.updateTime.format('YYYY-MM-DD HH:mm:ss') : null;

          console.log(formData)
          httpAction(httpurl, formData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message);
              that.$emit('ok');
            } else {
              that.$message.warning(res.message);
            }
          }).finally(() => {
            that.confirmLoading = false;
            that.close();
          })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    close() {
      this.$emit('close');
      this.visible = false;
    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field;
        this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
      }
      this.ipagination = pagination;
      this.loadData();
    },

    dayLimitEnableChange() {
      if (this.dayLimitEnable === 1) {
        this.dayLimitEnable = 2
      } else {
        this.dayLimitEnable = 1
      }
      this.chargeRulesForm.setFieldsValue({dayLimitEnable: this.dayLimitEnable})
    },
    freeTimeEnableChange() {
      if (this.freeTimeEnable === 1) {
        this.freeTimeEnable = 2
      } else {
        this.freeTimeEnable = 1
      }
      this.chargeRulesForm.setFieldsValue({freeTimeEnable: this.freeTimeEnable})
    },

    async getCarType(record) {
      let that = this
      that.confirmLoading = true
      that.CarTypeSelectOption = []
      if (!that.url.carTypeList) {
        this.$message.error("请设置url.carTypeList!")
        return
      }
      let params = {}
      params.parkCode = record.parkCode
      //加载数据 若传入参数1则加载第一页的内容
      await getAction(that.url.carTypeList, params).then( (res)  => {
        if (res.success) {
          var arr = [];
          res.result.forEach((car) => {
            arr.push({
              value: car.id,
              key: car.id,
              label: car.carTypeName
            })
          })
          that.CarTypeSelectOption = arr;
          if (that.CarTypeSelectOption.length !== 0) {
            let carTypeId = that.CarTypeSelectOption[0].value
            that.chargeRulesForm.setFieldsValue({
              carTypeId: carTypeId
            })
          }
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        that.confirmLoading = false
      })
    },
    async getChargeRules(record) {
      let that = this
      that.confirmLoading = true
      let params = {}
      params.parkCode = record.parkCode
      params.areaId = record.id
      //加载数据 若传入参数1则加载第一页的内容
      await getAction(this.url.getChargeRules, params).then((res) => {
        if (res.success) {
          if (res.result.records) {
            that.chargeRules = res.result.records
            let carTypeId = that.chargeRulesForm.getFieldValue("carTypeId")
            that.chargeRules.forEach(rule => {
              if (rule.carTypeId === carTypeId) {
                that.chargeRuleEdit(rule)
              }
            })
          } else {
            that.reset()
          }
        } else {
          that.$message.error("获取计费规则失败")
        }
        that.confirmLoading = false
      })
    },
    saveChargeRule() {
      const that = this;
      // 触发表单验证
      this.chargeRulesForm.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true;
          let httpurl = '';
          let method = '';
          if (that.chargeRule.id === null || that.chargeRule.id === undefined) {
            httpurl += that.url.addChargeRule;
            method = 'post';
          } else {
            httpurl += that.url.editChargeRule;
            method = 'put';
          }
          let formData = Object.assign(this.chargeRule, values);
          formData.dayLimit = formData.dayLimit * 100
          formData.parkCode = that.area.parkCode
          formData.areaId = that.area.id
          httpAction(httpurl, formData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message);
              that.$emit('ok');
              that.reset()
              that.getChargeRules(this.area)
            } else {
              that.$message.warning(res.message);
            }
          })
          that.confirmLoading = false;
        }
      })
    },

    getChargeRule(record) {
      const that = this
      let carTypeId = record
      this.chargeRule = {}
      this.reset()
      this.chargeRules.forEach(rule => {
        if (rule.carTypeId === carTypeId) {
          that.chargeRule = that.getObject(rule)
        }
      })
      if (that.chargeRule.id !== null && that.chargeRule.id !== undefined) {
        that.chargeRule.dayLimit = that.chargeRule.dayLimit / 100
        that.chargeRulesForm.setFieldsValue(pick(that.chargeRule, 'carTypeId', 'dayLimit', 'dayLimitEnable', 'twentyfourHourEnable', 'freeTime', 'freeTimeEnable'))
        that.dayLimitEnable = Number.parseInt(that.chargeRule.dayLimitEnable)
        that.freeTimeEnable = Number.parseInt(that.chargeRule.freeTimeEnable)
      }
    },
    chargeRuleDelete(record) {
      const that = this
      if (!this.url.chargeRuleDelete) {
        this.$message.error("请配置chargeRuleDelete")
        return
      }
      let params = {}
      params.id = record.id
      deleteAction(this.url.chargeRuleDelete, params).then(res => {
        if (res.success) {
          this.$message.success("删除成功")
          that.reset()
          this.getChargeRules(that.area)
        } else {
          this.$message.error("删除失败")
        }
      })
    },
    chargeRulesEdit(record) {
      this.EditForm = !this.EditForm
      this.$refs.chargeRulesModuleModal.init(record);
      this.chargeRule = this.getObject(record)

    },
    chargeRuleEdit(record) {
      let fromData = this.getObject(record)
      fromData.dayLimit = fromData.dayLimit / 100
      this.dayLimitEnable = fromData.dayLimitEnable
      this.freeTimeEnable = fromData.freeTimeEnable
      this.chargeRule = this.getObject(fromData)
      this.chargeRulesForm.setFieldsValue(pick(this.chargeRule, 'carTypeId', 'dayLimit', 'dayLimitEnable', 'twentyfourHourEnable', 'freeTime', 'freeTimeEnable'))
    },


    carTypeIdTrans(text) {
      let label = text
      this.CarTypeSelectOption.forEach(carType => {
        if (text === carType.value) {
          label = carType.label
        }
      })
      return label
    },
    getObject(object) {
      let ob = {}
      ob = Object.assign(ob, object)
      return ob
    },
    editOk(){
      this.EditForm = !this.EditForm
    }
  }
}
</script>

<style lang="less" scoped>
/** Button按钮间距 */
.ant-btn {
  margin-left: 30px;
  margin-bottom: 30px;
  float: right;
}

#chargeRulesModules {
  margin-bottom: 0px;
}

.chargeRulesModules {
  width: 100%;
}
/deep/ .ant-modal-footer{
  display: none;
}
/deep/ .ant-modal-body {
  padding: 8px 24px 24px;
  font-size: 14px;
  line-height: 1.5;
  word-wrap: break-word;
}

</style>